package com.lingjtx.common.core.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class LibreOfficeUtil {

    public static InputStream convertDocToDocx(String url) throws ExecutionException, InterruptedException, IOException {
        Path outputPath = convert(url, "docx");
        // 返回带自动删除标志的输入流
        if (outputPath != null) {
            return Files.newInputStream(outputPath, StandardOpenOption.DELETE_ON_CLOSE);
        }
        return null;
    }

    public static Path convert(String url, String format) throws ExecutionException, InterruptedException, MalformedURLException {
        // 构建统一的输出目录路径
        Path outputDir = Paths.get("/tmp/libre").toAbsolutePath();
        // 构建命令（保持通用）
        List<String> cmd = CommonCommandSet.CONVERT_DOCUMENT.build(format, outputDir.toString(), url);

        // 执行命令
        CommandExecutor.CommandResult result = CommandExecutor.builder()
                .command(cmd)
                .execute();

        if (result.isSuccess()) {
            // 提取文件名
            URL tempurl = URI.create(url).toURL();
            String fileName = new File(tempurl.getPath()).getName();
            // 构建生成的 .docx 文件路径（文件后缀替换为 .docx）
            String baseName = fileName.contains(".") ? fileName.substring(0, fileName.lastIndexOf('.')) : fileName;
            return outputDir.resolve(baseName + "." + format);
        }
        return null;
    }
}
